local http = require "resty.http";
local cjson = require "cjson"
local ngx=require "ngx";
local commonsConf = require "hgg-lua.commonsConf"



local IntegrationLog
IntegrationLog = function(premature)
    local logs_data = ngx.shared.logs_data;
    if logs_data then
        local tableKeys = logs_data:get_keys()
        local logKeyTbl={}
        -- 遍历table
        local reqb="[";
        local bol=false
        for key, value in pairs(tableKeys) do
            table.insert(logKeyTbl, value)
            if reqb == "[" then
                reqb=reqb..logs_data:get(value).." "
            else                
                reqb=reqb..","..logs_data:get(value)
            end
            bol=true
        end
        if reqb then
            reqb=reqb.."]"
        end
        if bol then
            logs_data:flush_all();
            local httpc = http.new();
            local res,err = httpc:request_uri(
                commonsConf.logs_index_intergration_server.url,
                {
                    method = "POST",
                    headers ={
                        ["Content-Type"] = "application/json"
                    },
                    body = reqb
                }            
            )
            if not res then
                ngx.log(ngx.ERR," 日志传输异常：",err)
            else
                ngx.log(ngx.ERR,ngx.localtime().."--日志采集成功");
            end
        end           
    end     
end
local delay=3;
if 0==ngx.worker.id() then
    local ok,err=ngx.timer.every(delay,IntegrationLog);
    if not ok then
        ngx.log(ngx.ERR,"启动日志采集异常");
        return;
    end
end